import React, { useEffect, useState } from 'react';
import { useSetState } from 'ahooks';
import moment from 'moment';
import { connect } from 'umi';

import { PageLoading, TRDefault } from '@/components/index.js';
import { useRem } from '@/hooks/index.js';
import Operate from './components/Operate';
import PointSearch from './components/PointSearch';

import {
  ChartLongTermPriceFocast,
  ChartHistoryBeforePrice,
  ChartMarketSupplyDemandRelationship,
  ChartSteamCoalMarket,
  ChartLongTermPriceFocast_shandong,
  ChartLongSupplyForecast,
} from './components/Charts';
import { HttpCode } from '#/utils/contacts.js';
import {
  fetchGetLongTermForecastPrice,
  fetchGetLongTermForecastSupply,
  fetchGetHistoryDayAheadPrice,
  fetchGetMarketSupDemRelation,
  fetchGetSteamCoalMarket,
  windSteamCoalFuture,
  getMarketSituation,
} from '@/pages/ETrade/MediumAndLongTermMarket/services.js';
import { descrip, pointConvert } from '../../constant.js';
import LongTermPriceFocast from './components/LongTermPriceFocast';
import HistoryBeforePrice from './components/HistoryBeforePrice';
import LongSupplyForecast from './components/LongSupplyForecast';
import MarketSupplyDemandRelationship from './components/MarketSupplyDemandRelationship';
import SteamCoalMarket from './components/SteamCoalMarket';
import * as echarts from 'echarts';
import 'echarts/extension/dataTool';
import _ from 'lodash';

import styles from './index.less';
const longTermTimeDate = [moment().add(1, 'days'), moment().add(1, 'month').endOf('month')];
const longSupplyTimeDate = [moment().add(1, 'days'), moment().add(1, 'month').endOf('month')];
const historyTimeDate = [
  moment().subtract(1, 'month').startOf('month'),
  moment().subtract(1, 'month').endOf('month'),
];
const marketSupDemRelationTimeDate = [moment(), moment().add(7, 'days')];

export const getAverageValueArr = (arr) => {
  let newArr = [];
  arr.forEach((v) => {
    newArr.push(_.mean(v));
  });
  return newArr;
};

export const LongTermElectricityPriceForecast = (props) => {
  const [longTermPriceFocastData, setLongTermPriceFocastData] = useState(),
    [historyDayAheadPrice, setHistoryDayAheadPrice] = useState(),
    [longSupplyForecastData, setLongSupplyForecastData] = useState(),
    [marketSupDemRelation, setMarketSupDemRelation] = useState(),
    [steamCoalMarket, setSteamCoalMarket] = useState(),
    [unitId, setUnitId] = useState(),
    [loading, setLoading] = useState(false),
    [longTermLoading, setlongTermLoading] = useState(),
    [longTermSupplyLoading, setLongTermSupplyLoading] = useState(),
    [historyLoading, setHistoryLoading] = useState(),
    [marketLoading, setMarketLoading] = useState(),
    [steamLoading, setSteamLoading] = useState(),
    [steamCoalOptions, setSteamCoalOptions] = useState([]),
    remSize = useRem(1920),
    [state, setState] = useSetState({
      refData: [],
    });

  /**建立echarts链接 */
  const getRef = (refData) => {
    const arr = [...state.refData];
    state.refData.push(refData);
    arr.push(refData);
    if (arr.length >= 2) {
      echarts.connect([...arr]);
    }
    setState({
      refData: arr,
    });
  };
  //长周期电价
  const getLongTermPriceFocast = async (values) => {
    setlongTermLoading(true);
    setLongTermPriceFocastData(null);
    let param = { provinceId: props.provinceId, stationId: unitId, marketId: props.marketId };
    // if (values) {
    if (props.provinceId === '37') {
      //山东省
      param.endDate = moment(values.date[1]).format('YYYY-MM-DD');
      param.startDate = moment(values.date[0]).format('YYYY-MM-DD');
      param.type = values.dateTimeorderType === '日期' ? 'date' : 'point';
    } else {
      param.endDate =
        values.tenDaysType === '月'
          ? moment(values.month).endOf('month').format('YYYY-MM-DD')
          : moment(values.month).set('date', values.tenDays.split('-')[1]).format('YYYY-MM-DD');
      param.startDate =
        values.tenDaysType === '月'
          ? moment(values.month).startOf('month').format('YYYY-MM-DD')
          : moment(values.month).set('date', values.tenDays.split('-')[0]).format('YYYY-MM-DD');
      param.forecastStep = values.tenDaysType === '月' ? 30 : 10;
      param.pointType = values.point;
    }

    const res = await fetchGetLongTermForecastPrice(param);
    setlongTermLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data?.length) return;
      let data = res.data;
      if (props.provinceId !== '37') {
        data = data[0];
        setLongTermPriceFocastData({
          XAXIS: data.referencePrice.map((t, i) => pointConvert(i + 1, parseInt(param.pointType))),
          realPrice: data.orgPrice,
          focastPrice: data.forecastPrice,
          referenPrice: data.referencePrice,
          maxPrice: data.upLimitPrice,
          minPrice: data.lowLimitPrice,
        });
      } else {
        const XAXIS = [],
          focastPrice = [];
        data.forEach((t) =>
          Object.entries(t).forEach((_t) =>
            _t[1].forEach((_t_, _i_) => {
              XAXIS.push(
                param.type === 'point'
                  ? `${moment(_t[0]).format('MMDD')} ${pointConvert(_i_ + 1, 24)}`
                  : `${moment(_t[0]).format('MMDD')}`,
              );
              focastPrice.push(_t_);
            }),
          ),
        );
        setLongTermPriceFocastData({
          XAXIS,
          focastPrice,
          isPoint: param.type === 'point',
        });
      }
    }
  };

  //历史日前电价
  const getHistoryDayAheadPrice = async (values) => {
    setHistoryLoading(true);
    setHistoryDayAheadPrice(null);
    let param = {
      provinceId: props.provinceId,
      stationId: unitId,
      timeOrder: values.point,
      startDate: moment(values.date[0]).format('YYYY-MM-DD'),
      endDate: moment(values.date[1]).format('YYYY-MM-DD'),
    };
    const res = await fetchGetHistoryDayAheadPrice(param);
    setHistoryLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data) return;
      const data = Object.entries(res.data);
      const XAXIS = [];
      const _historyBeforePrice = [];
      data.forEach((t, i) => {
        t[1].map((_t, _i) => {
          if (i === 0) {
            XAXIS.push(pointConvert(_i + 1, parseInt(param.timeOrder)));
            _historyBeforePrice[_i] = [_t];
          } else {
            _historyBeforePrice[_i].push(_t);
          }
        });
      });
      const averageValue = getAverageValueArr(_historyBeforePrice);

      setHistoryDayAheadPrice({
        XAXIS,
        historyBeforePrice: echarts?.dataTool.prepareBoxplotData(_historyBeforePrice, {
          boundIQR: 'none',
        }).boxData,
        averageValue,
      });
    }
  };

  // 长周期供需预测
  const getLongSupplyForecast = async (values) => {
    setLongTermSupplyLoading(true);
    setLongSupplyForecastData(null);
    let param = { provinceId: props.provinceId, stationId: unitId, marketId: props.marketId };
    param.endDate =
      values.tenDaysType === '月'
        ? moment(values.month).endOf('month').format('YYYY-MM-DD')
        : moment(values.month).set('date', values.tenDays.split('-')[1]).format('YYYY-MM-DD');
    param.startDate =
      values.tenDaysType === '月'
        ? moment(values.month).startOf('month').format('YYYY-MM-DD')
        : moment(values.month).set('date', values.tenDays.split('-')[0]).format('YYYY-MM-DD');
    param.forecastStep = values.tenDaysType === '月' ? 30 : 10;
    param.pointType = values.point;

    const res = await fetchGetLongTermForecastSupply(param);

    setLongTermSupplyLoading(false);

    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data?.length) return;
      let data = res.data;
      data = data[0];
      setLongSupplyForecastData({
        XAXIS: data.newEnergyPowerForecast.map((t, i) =>
          pointConvert(i + 1, parseInt(param.pointType)),
        ),
        actualProvincialLoad: data.actualProvincialLoad,
        provincialLoadForecast: data.provincialLoadForecast,
        actualNewEnergyPower: data.actualNewEnergyPower,
        newEnergyPowerForecast: data.newEnergyPowerForecast,
        actualTieLineLoad: data.actualTieLineLoad,
        tieLineLoadForecast: data.tieLineLoadForecast,
      });
    }
  };

  //市场供需
  /* const getMarketSupDemRelation = async (values) => {
    setMarketLoading(true);
    setMarketSupDemRelation(null);
    let param = {
      provinceId: props.provinceId,
      stationId: unitId,
      timeOrder: values.point,
      type: values.continuousAverage === '连续' ? 'con' : 'avg',
      startDate: moment(values.date[0]).format('YYYY-MM-DD'),
      endDate: moment(values.date[1]).format('YYYY-MM-DD'),
    };
    const res = await fetchGetMarketSupDemRelation(param);
    setMarketLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data) return;
      const data = res.data;
      const XAXIS = [],
        water = [],
        fire = [],
        newEnergy = [],
        newEnergy_1 = [],
        newEnergy_2 = [],
        newEnergy_3 = [];
      let count = 0; //空数组计数
      Object.entries(data).map((t, i) => {
        t[1].forEach((_t) => {
          count++;
          if (i === 0) {
            Array.from({ length: param.timeOrder }, (_t_, _i_) => {
              param.type === 'con'
                ? XAXIS.push(
                    `${moment(_t.date).format('MMDD')} ${pointConvert(
                      _i_ + 1,
                      parseInt(param.timeOrder),
                    )}`,
                  )
                : XAXIS.push(`${pointConvert(_i_ + 1, parseInt(param.timeOrder))}`);
            });
          }
          if (!_t.values?.length) {
            count--;
            Array.from({ length: param.timeOrder }, () => {
              if (t[0] === '新能源预测-DW') {
                newEnergy.push('-');
              }
              if (t[0] === '火电最小') {
                fire.push('-');
              }
              if (t[0] === '水电发力') {
                water.push('-');
              }
              if (t[0] === '新能源预测-XZ') {
                newEnergy_1.push('-');
              }
              if (t[0] === '新能源预测-DR') {
                newEnergy_2.push('-');
              }
              if (t[0] === '新能源预测-HN') {
                newEnergy_3.push('-');
              }
            });
          }
          (_t.values || []).forEach((_t_, _i_) => {
            if (t[0] === '新能源预测-DW') {
              newEnergy.push(_t_);
            }
            if (t[0] === '火电最小') {
              fire.push(_t_);
            }
            if (t[0] === '水电发力') {
              water.push(_t_);
            }
            if (t[0] === '新能源预测-XZ') {
              newEnergy_1.push(_t_);
            }
            if (t[0] === '新能源预测-DR') {
              newEnergy_2.push(_t_);
            }
            if (t[0] === '新能源预测-HN') {
              newEnergy_3.push(_t_);
            }
          });
        });
      });
      if (count < 1) {
        setMarketSupDemRelation(null);
      } else {
        setMarketSupDemRelation({
          XAXIS,
          water,
          fire,
          newEnergy,
          newEnergy_1,
          newEnergy_2,
          newEnergy_3,
        });
      }
    }
  }; */

  //动力煤
  const getSteamCoalMarket = async (values) => {
    setSteamLoading(true);
    setSteamCoalMarket(null);
    // let param = {
    //   provinceId: props.provinceId,
    //   stationId: unitId,
    //   type: values.kLine === '月K' ? 'month' : values.kLine === '周K' ? 'week' : 'day',
    // };
    const res = await getMarketSituation(values?.steamCoal);
    setSteamLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data?.length) return;
      const data = res.data;
      setSteamCoalMarket({
        XAXIS: data.map((t) => moment(t.date).format('YYYYMMDD')),
        openingPrice: data.map((t) => t.open),
        closingPrice: data.map((t) => t.close),
        highestPrices: data.map((t) => t.high),
        lowestPrices: data.map((t) => t.low),
        // upsAndDowns: data.map((t) => t.change),
        // amplitude: data.map((t) => t.amplitude),
        // ampP: data.map((t) => t.ampP), //振幅比例
        // percent: data.map((t) => t.percent), //涨跌比例
      });
    }
  };

  //默认请求
  const onSearch = async () => {
    setLoading(true);

    //动力煤列表
    const res = await windSteamCoalFuture();
    setSteamLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const data = res?.data?.map((t) => ({ label: t.name, value: t.id }));
      setSteamCoalOptions(data);
    }
    setLoading(false);
  };

  // 获取省份列表
  useEffect(() => {
    // props.fetchGetStationLevelThreeEffect(props.menuCode);
    onSearch();
  }, []);

  return (
    <div className={styles.LongTermElectricityPriceForecast}>
      <Operate onSearch={onSearch} unitId={unitId} setUnitId={setUnitId} />
      {loading ? (
        <PageLoading />
      ) : (
        <div className={styles.container}>
          <div className={styles.group}>
            <PointSearch
              title="长周期日均电价预测"
              topType={props.provinceId !== '37' ? 0 : 4}
              ModalComponent={(props) => <LongTermPriceFocast {...props} />}
              remSize={remSize}
              date={longTermTimeDate}
              unitId={unitId}
              disable={longTermPriceFocastData?.XAXIS.length}
              onChange={getLongTermPriceFocast}
              buttonPermissions={props.buttonPermissions}
            />
            {longTermLoading ? (
              <PageLoading />
            ) : longTermPriceFocastData?.XAXIS.length ? (
              //山东省id 37
              <>
                {props.provinceId !== '37' ? (
                  <ChartLongTermPriceFocast data={longTermPriceFocastData} scale={remSize / 100} />
                ) : (
                  <ChartLongTermPriceFocast_shandong
                    data={longTermPriceFocastData}
                    scale={remSize / 100}
                  />
                )}
              </>
            ) : (
              <TRDefault
                type="emptysm"
                message={
                  props.provinceId === '14' || props.provinceId === '37' ? '暂无数据' : descrip
                }
              />
            )}
          </div>
          <div className={styles.group}>
            <PointSearch
              title="历史日前电价"
              topType={1}
              date={historyTimeDate}
              remSize={remSize}
              unitId={unitId}
              disable={historyDayAheadPrice?.XAXIS.length}
              ModalComponent={(props) => <HistoryBeforePrice {...props} />}
              onChange={getHistoryDayAheadPrice}
            />
            {historyLoading ? (
              <PageLoading />
            ) : historyDayAheadPrice?.XAXIS.length ? (
              <>
                <ChartHistoryBeforePrice data={historyDayAheadPrice} scale={remSize / 100} />
              </>
            ) : (
              <TRDefault type="emptysm" />
            )}
          </div>
          <div className={styles.group}>
            <PointSearch
              title="长周期供需预测"
              topType={0}
              ModalComponent={(props) => <LongSupplyForecast {...props} />}
              remSize={remSize}
              date={longSupplyTimeDate}
              unitId={unitId}
              disable={longSupplyForecastData?.XAXIS.length}
              onChange={getLongSupplyForecast}
              buttonPermissions={props.buttonPermissions}
            />
            {longTermSupplyLoading ? (
              <PageLoading />
            ) : longSupplyForecastData?.XAXIS.length ? (
              <>
                <ChartLongSupplyForecast data={longSupplyForecastData} scale={remSize / 100} />
              </>
            ) : (
              <TRDefault
                type="emptysm"
                message={props.provinceId === '14' ? '暂无数据' : descrip}
              />
            )}

            {/*  <PointSearch
              title="市场供需关系"
              topType={2}
              unitId={unitId}
              remSize={remSize}
              date={marketSupDemRelationTimeDate}
              disable={marketSupDemRelation?.XAXIS.length}
              ModalComponent={(props) => <MarketSupplyDemandRelationship {...props} />}
              onChange={getMarketSupDemRelation}
            />
            {marketLoading ? (
              <PageLoading />
            ) : marketSupDemRelation?.XAXIS.length ? (
              <>
                <ChartMarketSupplyDemandRelationship
                  data={{ ...marketSupDemRelation, provinceId: props?.provinceId }}
                  scale={remSize / 100}
                />
              </>
            ) : (
              <TRDefault type="emptysm" />
            )} */}
          </div>
          <div className={styles.group}>
            <PointSearch
              title="动力煤市场行情"
              topType={3}
              remSize={remSize}
              unitId={unitId}
              disable={steamCoalMarket?.XAXIS.length}
              steamCoalOptions={steamCoalOptions}
              ModalComponent={(props) => <SteamCoalMarket {...props} />}
              onChange={getSteamCoalMarket}
            />
            {steamLoading ? (
              <PageLoading />
            ) : steamCoalMarket?.XAXIS.length ? (
              <>
                <div className={styles.toptip}>元/吨</div>
                <ChartSteamCoalMarket
                  data={steamCoalMarket}
                  scale={remSize / 100}
                  getRef={getRef}
                />
              </>
            ) : (
              <TRDefault type="emptysm" />
            )}
          </div>
        </div>
      )}
    </div>
  );
};

const mapStateToProps = ({ mediumAndLongTermMarket, global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
  provinceId: mediumAndLongTermMarket.provinceId,
  marketId: mediumAndLongTermMarket.marketId,
});

const mapDispatchToProps = (dispatch) => {
  return {
    fetchNewProvincesEffect: (payload) =>
      dispatch({ type: 'mediumAndLongTermMarket/fetchNewProvincesEffect', payload }),
    fetchGetStationLevelThreeEffect: (payload) =>
      dispatch({
        type: 'mediumAndLongTermMarket/fetchGetStationLevelThreeEffect',
        payload,
      }),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(LongTermElectricityPriceForecast);
